# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2011, Monash e-Research Centre
#   (Monash University, Australia)
# Copyright (c) 2010-2011, VeRSI Consortium
#   (Victorian eResearch Strategic Initiative, Australia)
# Copyright (c) 2011,2012 RMIT e-Research Office
#   (RMIT University, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    *  Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#    *  Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#    *  Neither the name of RMIT University, Monash University, 
#       the VeRSI, the VeRSI Consortium members, nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

#import sys
from urllib2 import HTTPError, URLError
import urllib2
import urllib
import logging

logger = logging.getLogger(__name__)

class HandleService:

    def _init_(self):
        logger.debug("initialize ...")

    def mint(self, authType, identifier, authDomain, appId,mintURL, hdlURL):
        """Create a new handle URL
        """
        #construct an user authentication info
        body = "<request name=\"mint\">\n\
             <properties>\n\
             <property name=\"authType\" value=\"" + authType + "\"/>\n\
             <property name=\"identifier\" value=\"" + identifier + "\"/>\n\
             <property name=\"authDomain\" value=\"" + authDomain + "\"/>\n\
             <property name=\"appId\" value=\"" + appId + "\"/>\n\
             </properties>\n\
             </request>"

        logger.debug("in mint")
        params = [('type',"URL"), ('value', hdlURL)]

        postString = mintURL + "?" + urllib.urlencode(params)
        #postString = mintURL
        
        #send the request to handle service
        return self.request(postString, (body))

    def request(self, postString, body):

        logger.debug('Requesting handle')
        logger.debug(postString)
        logger.debug(body)

        #connect to Handle Service
        req = urllib2.Request(postString, body)
        #open the connection
        
        response = None   
        logger.debug("req=%s" % req)
        try:
            response = urllib2.urlopen(req)
        except HTTPError, e:
            logger.error('The handle server could not fulfill the request.')
            logger.debug('Exception:%s', e)
            return ""
        except URLError, e:
            logger.error('Failed to reach the handle server.')
            logger.debug('Reason:%s', e.reason)
            return ""
        
        logger.debug('Handle response ' + str(response))

        data = response.read()
            #read the response
            #result = ''
            #while 1:
            #    data = response.read(1024)
            #    if not len(data):
            #        break
            #        result = result + repr(data)
            #        sys.stdout.write(data)
        logger.debug("data=%s" % data)
        return data
